//
//  NewWebViewController.m
//  Vpay
//
//  Created by 伟大大 on 2018/9/19.
//  Copyright © 2018年 丁伟佳. All rights reserved.
//

#import "NewWebViewController.h"
#import "UIImage+GIF.h"
#import "LoginViewController.h"
@interface NewWebViewController (){
    UIButton *rightNavBtn;
    
    int height;
    
    UIImageView * myImageView;
    
}

@end

@implementation NewWebViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    navigationImageView.hidden = YES;
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
        [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    self.title = self.LXtitle;
    self.view.backgroundColor = BACKCOLOR;
    self.navigationItem.leftBarButtonItem =[AppUtility getNavBtnItemLefBacktWith:@selector(backNative) andTarget:self];
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    navigationImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    
    //    //增加监听，当键盘出现或改变时收出消息
    //    [[NSNotificationCenter defaultCenter] addObserver:self
    //                                             selector:@selector(keyboardWillShow:)
    //                                                 name:UIKeyboardWillShowNotification
    //                                               object:nil];
    //
    //    //增加监听，当键退出时收出消息
    //    [[NSNotificationCenter defaultCenter] addObserver:self
    //                                             selector:@selector(keyboardWillHide:)
    //                                                 name:UIKeyboardWillHideNotification
    //                                               object:nil];
    //    [self initNavBtns];
    
    [self initViews];
    
    // Do any additional setup after loading the view.
    
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
- (void)initNavBtns {
    
    self.navigationItem.leftBarButtonItem =[AppUtility getNavBtnItemLefBacktWith:@selector(backNative) andTarget:self];
    //50 50
    
}
- (void)leftNavBtnClicked {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)initViews{
    
    
    
//    _arrowImage =myImageView;
    
    
//    self.hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//
//    self.hud.mode = MBProgressHUDModeCustomView;
//    self.hud.customView = [[UIImageView alloc]initWithImage:[AppUtility getLocalImage:@"set_safe"]];
    
//    self.hud.mode = MBProgressHUDModeIndeterminate;
    
    
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, [AppUtility screenWidth], [AppUtility screenHeight])];
    scrollView.backgroundColor = BACKCOLOR;
    scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:scrollView];
    
//    NSArray * myImages = [NSArray arrayWithObjects:
//                          [UIImage imageNamed:@"animation1.png"],
//                          [UIImage imageNamed:@"animation2.png"],nil];
    
    myImageView = [[UIImageView alloc]init];
    myImageView.image = [UIImage sd_animatedGIFNamed:@"load"];

    [myImageView setFrame:CGRectMake(scrollView.frame.size.width/2-144*theApp.autoSizeScaleX/2, scrollView.frame.size.height/2-144*theApp.autoSizeScaleY/2-44*theApp.autoSizeScaleY, 144.0f*theApp.autoSizeScaleX, 144.0f*theApp.autoSizeScaleY)];
    
    [scrollView addSubview:myImageView];
    
    _webView =[[UIWebView alloc] init];
    _webView.backgroundColor =BACKCOLOR;
    if ([self.mytype isEqualToString:@"1"]) {
        _webView.frame = CGRectMake(0, -27, [AppUtility screenWidth], [AppUtility screenHeight]-10*theApp.autoSizeScaleY);
    }else {
        _webView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height);

    }
    _webView.delegate =self;
    _webView.backgroundColor =[UIColor clearColor];
    
    NSURLRequest *request =[NSURLRequest  requestWithURL:[NSURL URLWithString:self.urlStr]] ;
    [_webView loadRequest:request];
    
    [scrollView addSubview:_webView];
    
    rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightNavBtn setFrame:CGRectMake1(0, 21, 80, 20)];
//    [rightNavBtn setImage:[AppUtility getLocalImage:@"Back"] forState:UIControlStateNormal];

    rightNavBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -2, 0, 72);
//    [rightNavBtn setTitle:@"交易记录" forState:UIControlStateNormal]; 10 19
//    rightNavBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//    [rightNavBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightNavBtn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
    [_webView addSubview:rightNavBtn];
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    height = keyboardRect.size.height;
    
    
    UIView *View = (UIView *)[self.view viewWithTag:10];
    
    [View setFrame:CGRectMake1(0, [AppUtility screenHeight]-height-200, [AppUtility screenWidth], 200)];
    UEXNSLog(@"%d",height);
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification{
    
    UIView *View = (UIView *)[self.view viewWithTag:10];
    
    UIView *alphaView = (UIView *)[self.view viewWithTag:11];
    [View setFrame:CGRectMake1(0, alphaView.frame.origin.x+alphaView.frame.size.height, [AppUtility screenWidth], 200)];
    
}
#pragma mark -
#pragma mark for delegate
#pragma mark -

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    NSDictionary *resultDict_hot =[NetUtility getDataWithURLStr:[NSString stringWithFormat:@"%@userid=%@&isApp=1",KURLUserInfo,@""] andPostStr:nil];
    
    UEXNSLog(@"URL = %@ ,resultDict_hot=%@",KURLUserInfo,resultDict_hot);
    
    if ([resultDict_hot[@"s"] intValue] == 303) {
        [self.navigationController.view makeToast:resultDict_hot[@"i"]];
        
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:KUDAppTDWNO];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:KUDAppTDWPass];
        
        LoginViewController *vc = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return NO;
        
    }
    
//    self.hud.hidden =NO;
    _webView.hidden =YES;
    
    return YES;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];

    
    // 1.获取页面标题
    
    NSString *string =@"document.title";
    //
    //    //获取当前页面的title 设置导航栏标题
    //
    //    NSString * title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    self.title = self.LXtitle;
    
    [webView stringByEvaluatingJavaScriptFromString:string];
    
//    if ([self.Neddtype isEqualToString:@"1"]) {
//
//        // 2.去掉页面标题
//
    NSString *str = @"document.getElementsByClassName('header_l')[0].remove();";

        // 3.根据标签类型获取指定标签的元素

//        [str appendString:@"var header = document.getElementsByTagName('a')[0];"];
//
//        [str appendString:@"header.parentNode.removeChild(header);"];//移除头部的导航栏
    

        [webView stringByEvaluatingJavaScriptFromString:str];
//
//    }else {
//
//    }
//
    
    [self performSelector:@selector(hidenaction)withObject:self afterDelay:0.1];
    
    
    
}

- (void)hidenaction{
    
    /// 开始加载时隐藏webview 加载完后显示，原因是 因为我们要去掉头标签，，去掉的方法是在网页加载完毕进行的，，添加一个延时现实的方法 可以隐藏掉网页先显示头标签又被移除的过程。使其看起来更自然一些
    
    _webView.hidden =NO;
    myImageView.hidden = YES;
//    self.hud.hidden =YES;
    
}
////用于授权验证的API，与AFN、UIWebView的授权验证API是一样的
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))
//
//    completionHandler{ completionHandler(NSURLSessionAuthChallengePerformDefaultHandling ,nil);
//
//}
//
//
//
//// 页面开始加载时调用
//-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
//
////    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    SLog(@"开始加载");
// }
//// 当内容开始返回时调用
//- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
//
////    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    SLog(@"内容开始返回");
//
//}
//// 页面加载完成之后调用
//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//    //这里修改导航栏的标题，动态改变
////    [self.navigationController setNavigationBarHidden:YES animated:YES];
//
////    self.title = webView.title;
//    SLog(@"加载完成");
//
//    [webView evaluateJavaScript:@"document.getElementsByClassName('page-header')[0].style.display='none'" completionHandler:nil];
//
//}
//- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
////    [self.navigationController setNavigationBarHidden:YES animated:YES];
//
//}
//// 页面加载失败时调用
//- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{ }
//// 接收到服务器跳转请求之后再执行
//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{ }
//// 在收到响应后，决定是否跳转
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
//    SLog(@"%@",webView);
//    SLog(@"%@",navigationResponse);
//    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
//    //这句是必须加上的，不然会异常
//    decisionHandler(actionPolicy);
//
//}
//// 在发送请求之前，决定是否跳转
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
//    //这句是必须加上的，不然会异常
//    decisionHandler(actionPolicy);
//}


#pragma mark -event

- (void)backNative {
    if ([_webView canGoBack]) {
        [_webView goBack];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//-(void)leftNavBtnClicked{
//    [self.navigationController popViewControllerAnimated:YES];
////    [theApp showBottomView];
//}
//-(void)rightNavBtnClicked{
//    if (_webView) {
//        [_webView reload];
//    }
//}
//-(void)preBtnClicked:(UIButton*)_inBtn{
//    //
//}
//-(void)nextBtnClicked:(UIButton*)_inBtn{
//
//}
//-(void)refreshBtnClicked:(UIButton*)_inBtn{
//    [_webView reload];
//}
//-(void)webViewDidStartLoad:(UIWebView *)webView{
//    [_refreshBtn setEnabled:NO];
//    [AppUtility showNetworkActivityIndicator:YES];
//}
//
//-(void)webViewDidFinishLoad:(UIWebView *)webView{
//    [_refreshBtn setEnabled:YES];
//     [AppUtility showNetworkActivityIndicator:NO];
//    if ([_webView canGoBack]) {
//        [_preBtn setEnabled:YES];
//    }else{
//         [_preBtn setEnabled:NO];
//    }
//    if ([_webView canGoBack]) {
//        [_preBtn setEnabled:YES];
//    }else{
//        [_preBtn setEnabled:NO];
//    }
//
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
